#include <stdlib.h>
#include <GL/glut.h>
#include "AnimatedSprite.hpp"
#include "../ResourceManagers/TextureManager.hpp"
#include "../ResourceManagers/TextureObject.hpp"
#include "../Extensions/ExtensionsLoader.hpp"

#include <iostream>

using namespace std;

AnimatedSprite::AnimatedSprite( string fileName, int iFramesNumber, int iFrameDuration, 
							   MVector3D& origin, bool bLoop, float fScaleX, float fScaleZ ) :
                               Sprite(fileName, origin, fScaleX, fScaleZ, TEXTURE_ALPHA)
{
	m_iFramesNum = iFramesNumber;
	m_iFrameDuration = iFrameDuration;
	m_bLoop = bLoop;
	m_iCurrFrame = 1;
	m_iLastTick = 0;
	setVisibility(true);

	m_fScaleX = fScaleX;
	m_fScaleZ = fScaleZ;
}

AnimatedSprite::~AnimatedSprite()
{
}

void AnimatedSprite::render()
{
	if(m_iCurrFrame > m_iFramesNum)
		return;

	glPushMatrix();
	glTranslatef(getPosition().x, getPosition().y, getPosition().z);

	TextureObject* texture = (TextureObject*)TextureManager::GetInstance()->GetTexture(m_name);

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture->GetTextureID());
	ExtensionsLoader::glActiveTextureARB(GL_TEXTURE0_ARB);

	if(texture->GetTextureType() == TEXTURE_ALPHA)
	{
		glAlphaFunc(GL_GREATER,0.0f);
		glEnable(GL_ALPHA_TEST);
	}

	glBegin(GL_QUADS);

	float x_min, x_max;

	x_min = x_max = 0.0;

	x_max =(float)m_iCurrFrame / m_iFramesNum;
	x_min = x_max - 1.0f/m_iFramesNum;

	float x, y, z;

	x = getPosition().x;
	y = getPosition().y;
	z = getPosition().z;

	//! left-top
	glTexCoord2f(x_min, 1.0);
	glVertex3f(-0.5*m_fScaleX,
		       0.0f,
			   -0.5*m_fScaleZ);

	//! left-bottom
	glTexCoord2f(x_min, 0.0);
	glVertex3f(-0.5*m_fScaleX,
		       0.0f,
			   0.5*m_fScaleZ);

	//! right-bottom
	glTexCoord2f(x_max, 0.0);
	glVertex3f(0.5*m_fScaleX,
		       0.0f,
			   0.5*m_fScaleZ);

	//! right-top
	glTexCoord2f(x_max, 1.0);
	glVertex3f(0.5*m_fScaleX,
		       0.0f,
			   -0.5*m_fScaleZ);

	glEnd();

	glDisable(GL_TEXTURE_2D);

	if(texture->GetTextureType() == TEXTURE_ALPHA)
		glDisable(GL_ALPHA_TEST);

	glPopMatrix();
}

void AnimatedSprite::update(clock_t tick)
{
	//cout << "currFrame: " << m_iCurrFrame << endl << endl;
	/*if(tick - m_iLastTick > m_iFrameDuration)
	{
		m_iLastTick = tick;*/
	if(m_iLastTick > m_iFrameDuration)
	{
		m_iLastTick = 0;
		++m_iCurrFrame;

		if(m_bLoop && m_iCurrFrame > m_iFramesNum)
			m_iCurrFrame = 1;
		else if( m_iCurrFrame > m_iFramesNum)
			m_iCurrFrame = m_iFramesNum + 1;
	}
	else
		m_iLastTick += tick;

	/*switch(m_currFrame)
	{
	case 1:
		m_scale = 0.9f;
		break;

	case 2:
		m_scale = 1.1f;
		break;

	case 3:
		m_scale = 1.0f;
		break;
	}*/

}

bool AnimatedSprite::isOver()
{
	if(!m_bLoop && m_iCurrFrame > m_iFramesNum)
		return true;

	return false;
}

void AnimatedSprite::restart()
{
	m_iCurrFrame = 1;
}

//EOF
